package com.kevin.spider.service;

import cn.hutool.core.collection.CollectionUtil;
import com.kevin.spider.domain.bo.CommonGood;
import com.microsoft.playwright.ElementHandle;
import com.microsoft.playwright.FileChooser;
import com.microsoft.playwright.Page;
import com.ruoyi.common.utils.CollectionUtils;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 张帆
 * @date 2025/6/16 17:56
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class SellerXhsService extends BaseSpiderService {
    private String xhsHomeUrl = "https://ark.xiaohongshu.com/app-system/home";

    private String xhsGoodUrl = "https://ark.xiaohongshu.com/app-item/list/shelf";

    public void goodUpload(CommonGood commonGood, Page page) {
        page.navigate(xhsGoodUrl);

        ElementHandle goodHomeContainer = getGoodHomeContainer(page);
        searchGood(goodHomeContainer, "6813297c3366f100017c1a48", page);

        Page createGoodPage = page.waitForPopup(() -> {
            clickCopyFirstGood(goodHomeContainer);
        });

        ElementHandle goodContainer = getGoodContainer(createGoodPage);

        setGoodName(goodContainer, commonGood.getGoodName());

        ElementHandle picAndTextContainer = getPicAndTextContainer(createGoodPage);
        openUploadPicDialog(picAndTextContainer);
        ElementHandle uploadPicDialogContainer = getUploadPicDialogContainer(createGoodPage);

        uploadPic(uploadPicDialogContainer, commonGood.getGoodMainPics(), createGoodPage);

        openUploadDetailPicDialog(picAndTextContainer);
        uploadPicDialogContainer = getUploadPicDialogContainer(createGoodPage);
        uploadPic(uploadPicDialogContainer, commonGood.getGoodDetailPics(), createGoodPage);

        saveDraft(page);

    }


    private ElementHandle getGoodHomeContainer(Page page) {
        return page.waitForSelector("//*[@id='ark-app-itemark-mount-container']");
    }

    private ElementHandle getCreateGoodButton(ElementHandle goodHomeContainer) {
        List<ElementHandle> targetSpans = goodHomeContainer.querySelectorAll("//span[contains(normalize-space(), '发布商品')]");
        return CollectionUtils.getFirst(targetSpans).querySelector("xpath=..");
    }

    private ElementHandle getGoodContainer(Page page) {
        return page.waitForSelector("//*[@id='anchor-cell-itemName']");
    }

    private void searchGood(ElementHandle goodHomeContainer, String keyword, Page page) {
        goodHomeContainer.waitForSelector("//input[@placeholder='请输入商品名称/ID/商品货号/商家编码，多条用逗号隔开']")
                .fill(keyword);
        page.keyboard().press("Enter");
    }

    private void clickCopyFirstGood(ElementHandle goodHomeContainer) {
        goodHomeContainer.querySelector("//span[contains(normalize-space(), '发布相似品')]")
                .querySelector("xpath=..")
                .click();
    }

    private void setGoodName(ElementHandle goodContainer, String goodName) {
        goodContainer.querySelector("//input[contains(@placeholder, '系统已自动在商品标题前拼接品牌名称，请勿重复填写品牌名称')]")
                .fill(goodName);
    }

    private ElementHandle getPicAndTextContainer(Page page) {
        return page.querySelector("//*[@id='anchor-图文信息']");
    }

    private void openUploadPicDialog(ElementHandle PicAndTextContainer) {
        PicAndTextContainer.querySelector("//span[contains(normalize-space(), '上传主图')]")
                .click();
    }

    private ElementHandle getUploadPicDialogContainer(Page page) {
        return page.waitForSelector("//div[@class='d-drawer-content']");
    }

    @SneakyThrows
    private void uploadPic(ElementHandle uploadPicDialogContainer, List<File> picFiles, Page page) {
        uploadPicDialogContainer.querySelector("//span[contains(normalize-space(), '上传本地图片')]")
                .click();

        // 监听文件选择对话框
        FileChooser fileChooser = page.waitForFileChooser(
                () -> {
                    page.querySelector("//span[contains(normalize-space(), '将文件或文件夹拖到此处，或点击上传')]")
                            .click();
                });
        page.waitForTimeout(1000);
        fileChooser.setFiles(picFiles.stream().map(File::toPath).toList().toArray(new Path[0]));
        //等待文件上传完成
        for (int i = 0; i < 10; i++) {
            List<ElementHandle> uploadRs = page.querySelectorAll("//span[contains(normalize-space(), '上传成功')]");
            if (CollectionUtil.size(uploadRs) >= picFiles.size()) {
                break;
            }
            Thread.sleep(2000);
        }
        // 触发文件选择操作（点击上传按钮）
        page.querySelector("//div[contains(@class, 'material-upload-drawer')]")
                .querySelector("//span[contains(normalize-space(), '确认')]")
                .click();

    }

    private ElementHandle getDetailContainer(Page page) {
        return page.querySelector("//div[@class='line-content']");
    }

    private void openUploadDetailPicDialog(ElementHandle detailContainer) {
        detailContainer.querySelector("//span[contains(normalize-space(), '上传图片')]")
                .click();
    }

    private void saveDraft(Page page) {
        page.querySelector("//span[contains(normalize-space(), '保存草稿')]")
                .click();
    }

}
